<template>
    <el-dialog :title="(mode==='view' ? '看图' : '选图') +'(键盘左、右方向键可用于切换)'"
               @close="onClose"
               :visible.sync="dialogVisible"
               v-loading="loading">
        <div @keyup.enter="keyDown">
            <div class="big-image" v-if="activeImage">
                <el-button @click="prevImage" class="prev-button"><i class="fa fa-chevron-left"></i></el-button>
                <el-button @click="nextImage" class="next-button"><i class="fa fa-chevron-right"></i></el-button>
                <img :src="smallUrl(activeImage.file)">
                <div>截图时间 {{activeImage.time}}</div>
            </div>
            <div style="text-align: center;margin: 10px 0;">
                <el-button @click="select" type="primary" v-if="mode ==='select'">{{isSelected()}}</el-button>
                <a v-if="activeImage" :href="url(activeImage.file)" target="_blank" class="el-button">查看大图</a>
                <el-button @click="close()">返回</el-button>
            </div>
            <template v-if="mode === 'view'">
                <div class="image-list">
                    <img v-for="(item,index) in data" :key="index"
                         @click="clickImage(index)"
                         :src="smallUrl(item.file)"
                         :class="imageClass(index)">
                </div>
            </template>
            <template v-else>
                <div>已选择图片</div>
                <div class="image-list" ref="selectedImageView">
                    <img v-for="(item,index) in selectedImages" :key="index"
                         @click="findImage(item.id)"
                         :src="smallUrl(item.file)">
                </div>
                <hr>
                <div>所有图片</div>
                <div class="image-list" ref="allImageView">
                    <img v-for="(item,index) in data" :key="index"
                         @click="clickImage(index)"
                         :src="smallUrl(item.file)"
                         :class="imageClass(index)">
                </div>
            </template>
        </div>
    </el-dialog>
</template>

<script>
    import _ from 'lodash';

    let keyDown;
    export default {
        name: "image_carousel",
        props: {
            visible: {type: Boolean, default: false},
            loading: {type: Boolean, default: true},
            data: {type: Array, required: true},
            value: {default: null},
            multi: {default: false,},
            mode: {default: 'select'},//view和select
        },
        data() {
            return {
                activeIndex: 0,
                selected: null,
                dialogVisible: false,
            };
        },
        methods: {
            keyDown(e) {
                if (e.code === 'ArrowLeft')
                    this.prevImage();
                else if (e.code === 'ArrowRight')
                    this.nextImage();
            },
            prevImage() {
                if (this.activeIndex > 0)
                    this.activeIndex--;
                else
                    this.activeIndex = this.data.length - 1;
                this.change();
            },
            nextImage() {
                if (this.activeIndex < this.data.length - 1)
                    this.activeIndex++;
                else
                    this.activeIndex = 0;
                this.change();
            },
            change() {
                this.$nextTick(() => {
                    const $img = this.$refs['allImageView'].children[this.activeIndex];
                    if (!$img) return;
                    $img.scrollIntoView();
                });
            },
            url(file) {
                return `/pic/${file}/预览.jpeg`;
            },
            smallUrl(file) {
                return `/pic/${file}_small`;
            },
            open() {
                keyDown = this.keyDown.bind(this);
                window.addEventListener('keyup', keyDown);
                this.dialogVisible = true;
                this.$emit('update:visible', true);
            },
            close() {
                window.removeEventListener('keyup', keyDown);
                this.dialogVisible = false;
                this.activeIndex = 0;
                this.$emit('input', this.selected);
                this.$emit('change', _.find(this.data, {id: this.selected}));
                this.$emit('update:visible', false);
            },
            onClose() {
                this.close();
            },
            imageClass(index) {
                let selected = this.data[index].selected, active = this.activeIndex === index;
                return {selected, active};
            },
            select() {
                const item = this.data[this.activeIndex];
                if (this.multi) {
                    const index = this.selected.indexOf(item.id);
                    if (index === -1) {
                        this.selected.push(item.id);
                    }
                    else
                        this.selected.splice(index, 1);

                    item.selected = !item.selected;
                } else {
                    if (item.selected) {
                        this.selected = null;
                    } else {
                        this.selected = item.id;
                        this.data.forEach(pic => {
                            pic.selected = false;
                        });
                    }
                    item.selected = !item.selected;
                }
                this.$nextTick(() => {
                    this.$forceUpdate();
                });
            },
            isSelected() {
                const item = this.data[this.activeIndex];
                if (!item)
                    return '选择';
                if (this.multi) {
                    return this.selected.indexOf(item.id) === -1 ? '选择' : '取消选择';
                } else {
                    return this.selected !== item.id ? '选择' : '取消选择';
                }
            },
            clickImage(index) {
                this.activeIndex = index;
            },
            findImage(id) {
                let item = _.find(this.data, {id});
                this.activeIndex = this.data.indexOf(item);
                this.change();
            },
        },
        computed: {
            activeImage() {
                if (!this.data)
                    return null;
                const item = this.data[this.activeIndex];
                if (!item)
                    return null;
                return {
                    time: moment(item.created_at).format('YYYY年MM月DD日 HH点mm分ss秒'),
                    file: item.file,
                    id: item.id,
                    selected: item.selected
                };
            },
            selectedImages() {
                return this.data.filter(pic => pic.selected);
            },
            unSelectedPic() {
                return this.data.filter(pic => !pic.selected);
            },
        },
        watch: {
            visible(val) {
                if (val && this.dialogVisible !== true)
                    this.open();
                else if (this.dialogVisible !== false)
                    this.close();
            },
            value(val) {
                console.log({val});
                this.selected = val;
            },
        },
    }
</script>

<style scoped>
    .big-image {
        position: relative;
        text-align: center;
    }

    .big-image img {
        height: 300px;
    }

    .big-image .prev-button {
        position: absolute;
        top: 40%;
        left: 10%;
    }

    .big-image .next-button {
        position: absolute;
        top: 40%;
        right: 10%;
    }

    .image-list {
        cursor: auto;
        position: relative;
        height: 70px;
        overflow: hidden;
        display: flex;
        align-items: flex-end;
    }

    .image-list img {
        position: relative;
        width: 92px;
        border: 4px solid transparent;
    }

    .image-list img.selected {
        top: -5px !important;
        border-color: #67C23A;
    }

    .image-list img:hover, .image-list img.active {
        z-index: 2;
        border-color: #409EFF;
    }

    .image-list img:hover {
        z-index: 3;
    }
</style>